import PhysiologicalMonitoring from '@/components/PhysiologicalMonitoring';
import { get_patient_call_log, get_patient_message, get_patient_sickbed_log, get_sickbed_info } from '@/services/sickbeds';
import age from '@/utils/age';
import timeToHms from '@/utils/time';
import { ActionType, ProColumns, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { Button, Divider, Modal, Spin, Tabs, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react'
import AddRecord from './AddRecord';
import CheckRecord from './CheckRecord';
import CheckVideo from './CheckVideo';

interface Iprops {
    isShowInfoModal: (show: boolean) => void;
    isInfoModalOpen: boolean;
    actionRef: React.MutableRefObject<ActionType | undefined>;
    id: number | undefined
}
type GithubIssueItem = {
    id: number;
    time: string;
    call_type: number;
    create_time: string;
    status: number;
    status_d: string;
    total_time: number;
    remark: string;
    video_url: string;
    update_time: string;
};
const SickbedsInfo = (props: Iprops) => {
    const { isInfoModalOpen, isShowInfoModal, id, actionRef } = props
    const recordActionRef = useRef<ActionType>();

    // 存储病床详情
    const [sickbedsInfo, setSickbedsInfo] = useState<any>(undefined);
    // 存储病床编号
    const [sickbedsCode, setSickbedsCode] = useState();
    // 存储患者id
    const [patientId, setPatientId] = useState();
    // 存储添加记录模态框的状态
    const [isAddRecordModalOpen, setIsAddRecordModalOpen] = useState(false);
    // 存储查看记录模态框的状态
    const [isCheckRecordModalOpen, setIsCheckRecordModalOpen] = useState(false);
    // 存储通话记录id
    const [callLogId, setCallLogId] = useState<number>();
    // 存储备注信息
    const [remark, setRemark] = useState<string>();
    // 存储添加记录时间
    const [time, setTime] = useState<string>();
    // 查看指导视频模态框
    const [checkVideo, setCheckVideo] = useState(false);
    // 存储视频url
    const [videoUrl, setVideoUrl] = useState('');

    // 控制添加记录模态框的显示与隐藏
    const isShowAddRecord = (status: boolean) => {
        setIsAddRecordModalOpen(status)
    }
    // 控制查看记录模态框的显示与隐藏
    const isShowCheckRecord = (status: boolean) => {
        setIsCheckRecordModalOpen(status)
    }
    // 控制查看录制视频模态框的显示与隐藏
    const isShowCheckVideoModal = (status: boolean) => {
        setCheckVideo(status);
    };
    // 页面初始化
    useEffect(() => {
        const getData = async () => {
            if (id) {
                let res: any = await get_sickbed_info({ id })
                console.log('病床详情', res);

                if (res.code == 200) {
                    setSickbedsInfo(res.data);
                    setSickbedsCode(res.data.code);
                    setPatientId(res.data.patient_id)
                }
            }
        }
        getData()
    }, [])

    // 建床记录列表
    const getSickBedsLogs = async (params: {
        pageSize?: number | undefined;
        current?: number | undefined;
        keyword?: string | undefined;
    }) => {
        //默认分页参数和后端接口字段不匹配
        let request_body = {
            ...params,
            patient_id: sickbedsInfo.patient_id ? sickbedsInfo.patient_id : '',
            current: params.current,
            pageSize: params.pageSize,
        };
        let res = await get_patient_sickbed_log(request_body)
        console.log('建床记录列表', res);
        return {
            data: res.data.list,
            success: true,
            total: res.data.total_count,
        };
    }

    // 患者家庭病床通话记录列表
    const getPatientCallLog = async (params: {
        pageSize?: number | undefined;
        current?: number | undefined;
        keyword?: string | undefined;
    }) => {
        //默认分页参数和后端接口字段不匹配
        let request_body = {
            ...params,
            patient_id: sickbedsInfo.patient_id,
            current: params.current,
            pageSize: params.pageSize,
        };
        let res = await get_patient_call_log(request_body)
        console.log('患者家庭病床通话记录列表', res);
        return {
            data: res.data.list,
            success: true,
            total: res.data.total_count,
        };
    }
    // 预警消息列表
    const getPatientMessage = async (params: {
        pageSize?: number | undefined;
        current?: number | undefined;
        keyword?: string | undefined;
    }) => {
        //默认分页参数和后端接口字段不匹配
        let request_body = {
            ...params,
            patient_id: sickbedsInfo.patient_id,
            current: params.current,
            pageSize: params.pageSize,
        };
        let res = await get_patient_message(request_body)
        console.log('患者家庭病床预警消息列表', res);
        return {
            data: res.data.list,
            success: true,
            total: res.data.total_count,
        };
    }
    // 呼叫跳转  type video/audio 视频/语音
    const send_call = (type: string) => {
        console.log(type);
        const width = type == 'video' ? 960 : 800; // 自定义宽度
        const height = 601; // 自定义高度
        const left = screen.width / 2 - width / 2;
        const top = screen.height / 2 - height / 2;
        if (sickbedsCode && patientId) {
            window.open(`/familySickbeds/EstablishedSickbeds/${type}?code=${sickbedsCode}&patientId=${patientId}`, '', `width=${width},height=${height},left=${left},top=${top}`);
        }
    };
    window.addEventListener('message', function (event: any) {
        // 在父窗口中显示子窗口发来的消息
        console.log('fff', event.data);
        if (event.data == 'refreshCallList') {
            recordActionRef.current?.reload();
        }
    });

    // 建床记录
    const columns: ProColumns<GithubIssueItem>[] = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: 'index',
            hideInSearch: true,
            align: 'center',
        },
        {
            title: '病床编号',
            dataIndex: 'sickbed_code',
            align: 'center',
        },
        {
            title: '建床时间',
            dataIndex: 'create_time',
            align: 'center',
        },
    ];
    // 通话记录
    const columns1: ProColumns<GithubIssueItem>[] = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: 'index',
            hideInSearch: true,
            align: 'center',
        },
        {
            title: '病床编号',
            dataIndex: 'sickbed_code',
            align: 'center',
        },
        {
            title: '通话类型',
            dataIndex: 'type',
            align: 'center',
            valueEnum: {
                1: {
                    text: '语音'
                },
                2: {
                    text: '视频'
                }
            }
        },
        {
            title: '通话时长',
            dataIndex: 'time',
            align: 'center',
            render: (_, record) => {
                if (record.status != 3) {
                    return record.status == 0 ? '待响应' : record.status == 1 ? '通话中' : record.status == 2 ? '拒接' : "已取消";
                } else {
                    return timeToHms(record.time);
                }
            },
        },
        {
            title: '通话时间',
            dataIndex: 'create_time',
            align: 'center',
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            align: 'center',
            render: (text, record, _, action) => (
                <>
                    {
                        !record.remark ?
                            <Button
                                key="add"
                                type='link'
                                onClick={() => {
                                    setCallLogId(record.id);
                                    isShowAddRecord(true);
                                }}
                            >
                                添加记录
                            </Button> : <Button
                                key="checkRecord"
                                type='link'
                                onClick={() => {
                                    setRemark(record.remark);
                                    setTime(record.update_time);
                                    isShowCheckRecord(true);
                                }}
                            >
                                查看记录
                            </Button>
                    }
                    {record.video_url ?
                        <Button
                            key="check"
                            type='link'
                            onClick={() => {
                                setVideoUrl(record.video_url);
                                isShowCheckVideoModal(true);
                            }}
                        >
                            查看视频
                        </Button> : <></>}

                </>

            ),
        }
    ];

    // 预警提醒
    const columns2: ProColumns<GithubIssueItem>[] = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: 'index',
            hideInSearch: true,
            align: 'center',
        },
        {
            title: '预警信息',
            dataIndex: 'message',
            align: 'center',
        },
        {
            title: '预警时间',
            dataIndex: 'create_time',
            align: 'center',
        },
    ]
    return (
        <Modal
            title="详情"
            centered
            open={isInfoModalOpen}
            onCancel={() => isShowInfoModal(false)}
            width={1200}
            destroyOnClose={true}
            footer={null}
        >
            <Divider />
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Button
                    key="audio"
                    style={{ padding: '0 12px', margin: '0 20px 20px 0' }}
                    type="primary"
                    onClick={() => send_call('audio')}
                >
                    语音通话
                </Button>
                <Button
                    key="video"
                    style={{ padding: '0 12px', margin: '0 20px 20px 0' }}
                    type="primary"
                    onClick={() => send_call('video')}
                >
                    视频通话
                </Button>
            </div>
            {sickbedsInfo === undefined ? <div
                style={{
                    margin: '20px 0',
                    marginBottom: '20px',
                    padding: '30px 50px',
                    textAlign: 'center',
                }}
            >
                <Spin size="large" />
            </div> : <> <ProDescriptions
                dataSource={sickbedsInfo}
                title='病床信息'
                column={3}
                columns={[
                    {
                        title: '病床编号',
                        key: 'code',
                        dataIndex: 'code',
                    },
                    {
                        title: '创建人',
                        key: 'manage_name',
                        dataIndex: 'manage_name',
                    },
                    {
                        title: '创建时间',
                        key: 'create_time',
                        dataIndex: 'create_time',
                    },
                    {
                        title: '责任医生',
                        key: 'doctor_name',
                        dataIndex: 'doctor_name',
                        render: (_, record) => {
                            return record.doctor_list
                                .map((item: any) => item.username)
                                .join()
                        }
                    },
                ]}
            ></ProDescriptions>
                <ProDescriptions
                    dataSource={sickbedsInfo}
                    title='患者信息'
                    column={3}
                    columns={[
                        {
                            title: '手机号',
                            key: 'phone',
                            dataIndex: 'phone',
                        },
                        {
                            title: '姓名',
                            key: 'username',
                            dataIndex: 'username',
                        },
                        {
                            title: '性别',
                            key: 'sex',
                            dataIndex: 'sex',
                            valueEnum: {
                                0: {
                                    text: '未知',
                                },
                                1: {
                                    text: '男',
                                },
                                2: {
                                    text: '女',
                                },
                            },
                        },
                        {
                            title: '身份证号',
                            key: 'id_card',
                            dataIndex: 'id_card',
                        },
                        {
                            title: '年龄',
                            key: 'birth',
                            dataIndex: 'birth',
                            render: (_, record) => age(record.birth),
                        },
                        {
                            title: '居住地址',
                            key: 'patient_address',
                            dataIndex: 'patient_address',
                            render: (_, record) => {
                                return (
                                    record.province_name +
                                    record.city_name +
                                    record.area_name +
                                    record.family_address
                                );
                            },
                        },
                        {
                            title: '风险等级',
                            key: 'level',
                            dataIndex: 'level',
                            valueEnum: {
                                1: {
                                    text: '蓝色',
                                },
                                2: {
                                    text: '黄色',
                                },
                                3: {
                                    text: '红色',
                                },
                            },
                        },
                    ]}
                ></ProDescriptions>
                <Tabs
                    style={{
                        minHeight: "600px"
                    }}
                    defaultActiveKey="预警提醒"
                    items={[
                        {
                            key: '预警提醒',
                            label: '预警提醒',
                            children: (
                                <ProTable<GithubIssueItem>
                                    columns={columns2}
                                    cardBordered
                                    request={async (params = {}) => getPatientMessage(params)}
                                    editable={{
                                        type: 'multiple',
                                    }}
                                    rowKey={(record) => record.id}
                                    search={false}
                                    options={false}
                                    pagination={{
                                        pageSize: 10,
                                    }}
                                    dateFormatter="string"
                                    headerTitle=""
                                />
                            ),
                        },
                        {
                            key: '生理监测',
                            label: '生理监测',
                            children: (
                                <PhysiologicalMonitoring
                                    patientId={sickbedsInfo.patient_id}
                                ></PhysiologicalMonitoring>
                            ),
                        },
                        {
                            key: '建床记录',
                            label: '建床记录',
                            children: (
                                <ProTable<GithubIssueItem>
                                    columns={columns}
                                    cardBordered
                                    request={async (params = {}) => getSickBedsLogs(params)}
                                    editable={{
                                        type: 'multiple',
                                    }}
                                    rowKey={(record) => record.id}
                                    search={false}
                                    options={false}
                                    pagination={{
                                        pageSize: 10,
                                    }}
                                    dateFormatter="string"
                                    headerTitle=""
                                />
                            ),
                        },
                        {
                            key: '通话记录',
                            label: '通话记录',
                            children: (
                                <ProTable<GithubIssueItem>
                                    columns={columns1}
                                    actionRef={recordActionRef}
                                    cardBordered
                                    request={async (params = {}) => getPatientCallLog(params)}
                                    editable={{
                                        type: 'multiple',
                                    }}
                                    rowKey={(record) => record.id}
                                    search={false}
                                    options={false}
                                    pagination={{
                                        pageSize: 10,
                                    }}
                                    dateFormatter="string"
                                    headerTitle=""
                                />
                            ),
                        },
                    ]}
                /></>}
            {/* 添加记录模态框 */}
            {isAddRecordModalOpen ? <AddRecord isAddRecordModalOpen={isAddRecordModalOpen} isShowAddRecord={isShowAddRecord} id={callLogId} recordActionRef={recordActionRef}></AddRecord> : <></>}
            {/* 查看记录模态框 */}
            {isCheckRecordModalOpen ? <CheckRecord isCheckRecordModalOpen={isCheckRecordModalOpen} isShowCheckRecord={isShowCheckRecord} remark={remark} time={time}></CheckRecord> : <></>}
            {/* 查看视频模态框 */}
            {checkVideo ? <CheckVideo checkVideo={checkVideo} isShowCheckVideoModal={isShowCheckVideoModal} videoUrl={videoUrl}></CheckVideo> : <></>}
        </Modal>
    )
}
export default SickbedsInfo